﻿#include "Controller.h"
#include "Producer.h"
#include "Customer.h"
#include <QDebug>


QQueue<QString> Controller::queue;

Controller::Controller(QObject *parent)
    : QObject{parent}
{
    qDebug() << "Controller Running in:" << QThread::currentThreadId();

    producer = new Producer();
    connect(producer, &Producer::sendMsg, this, [&](const QString & msg) {
        pdBuffer.append(msg);
    });

    customer = new Customer();
    connect(customer, &Customer::sendMsg, this, [&](const QString & msg) {
        ctBuffer.append(msg);
    });

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]() {
        if (!pdBuffer.isEmpty()) {
            emit producerLog(pdBuffer.join("\n"));
            pdBuffer.clear();
        }
        if (!ctBuffer.isEmpty()) {
            emit customerLog(ctBuffer.join("\n"));
            ctBuffer.clear();
        }
    });
}

Controller::~Controller()
{
    producer->deleteLater();
    customer->deleteLater();
}

void Controller::runTask()
{
    timer->start(800);
    producer->start();
    customer->start();
}
